package com.zzk.www.nettyServer.initialize;

import com.zzk.www.nettyServer.handler.ZZKChatServerHandler;
import com.zzk.www.nettyServer.handler.ZZKHttpRequestHandler;
import com.zzk.www.nettyServer.handler.ZZKWebSocketServerProtocolHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Created by zzk on 2017/12/16.
 */
public class ChatServerInitialize extends ChannelInitializer<SocketChannel> {


    //当客户端连接服务器时，netty会自动调用者初始化器的initChannel方法
    protected void initChannel(SocketChannel channel) throws Exception {

        System.out.println("有客户端连入："+channel.remoteAddress());

        ChannelPipeline pipeline = channel.pipeline();

        pipeline.addLast(new HttpServerCodec());//将请求和应答消息编码或者解码为http协议的消息  (之后的channelread中的泛型,类型已经变为httprequest)
        pipeline.addLast(new HttpObjectAggregator(64*1024));//http请求分包
        pipeline.addLast(new ChunkedWriteHandler());//向客户端发送html5的页面文件
        pipeline.addLast(new ZZKHttpRequestHandler());//区分http请求,读取html页面并写回客户端浏览器
        pipeline.addLast(new ZZKWebSocketServerProtocolHandler());//会拦截该地址的请求,会区分访问是控制针访问还是数据帧访问,数据帧访问会交给自己的控制器处理
        pipeline.addLast(new ZZKChatServerHandler());//向客户端发送数据
    }
}
